package com.aiyun.securiy.login.web;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


import com.aiyun.securiy.login.security.SecurityUtils;
import com.aiyun.securiy.login.security.UserList;
import com.aiyun.securiy.login.security.custom.CustomAuthenticationProvider;
import com.aiyun.securiy.login.security.custom.CustomRequestFilter;
import com.aiyun.securiy.login.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller to authenticate users.
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class UserJWTController {


	private final CustomAuthenticationProvider customAuthenticationProvider;

	private final AsyncService asyncService;

	private final UserList userList;

	public UserJWTController(CustomAuthenticationProvider customAuthenticationProvider, AsyncService asyncService, UserList userList) {
		this.customAuthenticationProvider = customAuthenticationProvider;
		this.asyncService = asyncService;
		this.userList = userList;
	}

	@PostMapping("/authenticate")
	@Cacheable(cacheNames = "authorize", key = "#username + '_' + #password")
    public String authorize(String username, String password) {
		log.info("用户{}请求登录....", username);
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
				username,
				password
		);
        Authentication authentication = customAuthenticationProvider.authenticate(authenticationToken);
		String token = UUID.randomUUID().toString();
		userList.setToken(token, authentication);
		SecurityContextHolder.getContext().setAuthentication(authentication);
		return token;
    }


    @GetMapping("/account")
	@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ResponseEntity<String> getCurrentUser() throws InterruptedException, ExecutionException {
		String s = CustomRequestFilter.currentUser.get();
		log.info("current user is {}", s);
		val currentUser = SecurityUtils.getCurrentUser();
		log.info("Spring Security user is : {}", currentUser);
		SecurityContext context = SecurityContextHolder.getContext();
		Object principal = context.getAuthentication().getPrincipal();
		return ResponseEntity.ok(principal.toString());
	}
}
